package cn.hhhy.service.impl;

import cn.hhhy.mapper.EstateMapper;
import cn.hhhy.mapper.User_VillageMapper;
import cn.hhhy.pojo.*;
import cn.hhhy.service.EstateService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EstateServiceImpl implements EstateService {
    @Autowired
    private EstateMapper estateMapper;
    @Autowired
    private User_VillageMapper userVillageMapper;
    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();

        IPage<Estate> page = estateMapper.selectPage(new Page<>(currentPage,pageSize),
                Wrappers.lambdaQuery(Estate.class)
                        .like(!Strings.isEmpty(queryString), Estate::getUid, queryString)
                        .or()
                        .like(!Strings.isEmpty(queryString), Estate::getVid, queryString)
        );
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public Estate findById(Integer id) {
        return estateMapper.selectById(id);
    }

    @Override
    public void add(Estate estate) {
        User_Village userVillage  = new User_Village();
        userVillage.setVid(estate.getVid());
        userVillage.setUid(estate.getUid());
        userVillageMapper.insert(userVillage);
        estateMapper.insert(estate);
    }

    @Override
    public void delete(Integer id) {
        estateMapper.deleteById(id);
    }

    @Override
    public void update(Estate estate) {
        userVillageMapper.delete(Wrappers.lambdaQuery(User_Village.class).eq(User_Village::getUid,estate.getUid()).eq(User_Village::getVid,estate.getVid()));
        User_Village userVillage  = new User_Village();
        userVillage.setVid(estate.getVid());
        userVillage.setUid(estate.getUid());
        userVillageMapper.insert(userVillage);
        estateMapper.updateById(estate);
    }
}
